export default {
  namespaced: true,

  state: () => ({
    // 购物车的数组， 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }   
       cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  // 模块的 mutations 方法
    mutations: {
      // 将商品添加到购物车
      addToCart(state, goods) {
        const findResult = state.cart.find((x) => x.goods_id === goods.goods_id)
        if (!findResult) {
          state.cart.push(goods)
        } else {
          findResult.goods_count++
        }  
        this.commit('my_cart/saveCartStore')
        console.log(state.cart);
      },
      // 将购物车数量持久化存储到本地
      saveCartStore(state){
        uni.setStorageSync('cart', JSON.stringify(state.cart))
      },
      // 更新购物车中商品的勾选状态
      updateGoodsState(state, goods) {
        const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
        if (findResult) {
          findResult.goods_state = goods.goods_state
          this.commit('my_cart/saveCartStore')
        }
      },
      // 修改购物车中商品的数量
      updateGoodsNum(state,goods){
        // console.log(state.cart);
        const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
        if (findResult) {
          findResult.goods_count = goods.goods_count
          this.commit('my_cart/saveCartStore')
        }
      },
      // 删除购物车商品
      removeCart(state,goods_id){
        state.cart = state.cart.filter(x => x.goods_id !== goods_id)
        this.commit('my_cart/saveCartStore')
      },
      // 更新商品全选状态
      updateAllStatus(state,newStatus){
        state.cart.forEach(item => item.goods_state = newStatus) 
      }
    },
    getters:{
      // 动态计算购物车商品数量
      total(state){
        let c =0
        state.cart.forEach(x => {c+=x.goods_count})
        return c
      },
      // 动态渲染已勾选商品数量
      checkedCount(state){
        return state.cart.filter(x => x.goods_state).reduce((total,item) => total +=item.goods_count, 0)
      },
      // 计算购物车商品总价格
      checkedGoodsAmount(state){
        const res = state.cart.filter(item => item.goods_price === 0)
        res.map((item)=>{item.goods_price = 99.99})
        const arr = [...res,...state.cart]
        // 先过滤出已勾选商品
        return arr.filter(item => item.goods_state)
                          // 计算已勾选商品价格
                        .reduce((total,x) => total +=x.goods_count * x.goods_price , 0)
                        // 保留两位小数
                        .toFixed(2)
      }
    }
}